import { createRouter, createWebHistory } from 'vue-router'
import { showToast } from 'vant';
import HomeView from '../views/HomeView/index.vue'
import LoginView from '../views/LoginView/index.vue'
import ErrorView from '../views/ErrorView/index.vue'
import Router from './Router'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: '首页',
      component: HomeView,
      redirect: '/home',//重定向
      children: Router
    },
    {
      path: '/login',
      name: '登录',
      component: LoginView,
    },
    {
      path: '/:catchAll(.*)',
      name: '404',
      component: ErrorView,
    },
  ]
})
// 获取token
const Token = () => {
  const token = localStorage.getItem('token'); // 从本地存储中获取 token
  return !!token; // 如果 token 存在，则返回 true，否则返回 false
}

// 超时
const Overtime = () => {
  const dayDate = 2 * 60 * 60 * 1000;
  const oldDate = localStorage.getItem('date')  || null;
  const newDate = Date.now();
  if (oldDate && newDate - Number(oldDate) >= dayDate) {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    localStorage.removeItem('date');
    showToast('身份已过期,请重新登录');
    return
  } else {
    return
  }
}

// 全局前置守卫
router.beforeEach((to, from, next) => {
  Overtime();
  if (!Token() && to.path !== '/login') {
    next('/login')
  } else {
    next()
  }
});
export default router
